package novel.front.novellist.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import lombok.extern.slf4j.Slf4j;
import novel.common.utils.EmojiConverterUtil;
import novel.common.utils.HttpClientUtil;
import novel.common.utils.OkttpUtil;
import novel.front.novellist.dao.AppsoMapper;
import novel.front.novellist.entity.Appso;
import novel.front.novellist.entity.Kuaixun;
import novel.front.novellist.entity.LiebaoApp;
import novel.front.novellist.service.KuaixunService;
import novel.front.novellist.service.LiebaoAppService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("web")
public class Spridtest {

    @Resource
    private LiebaoAppService liebaoAppService;

    @Resource
    private KuaixunService kuaixunService;

    @Resource
    private AppsoMapper appsoMapper;

    @RequestMapping("test")
    public void spirderTask11() {
        String url = "https://sso.ifanr.com/api/v5/trochili/miniapp/?tag=&limit=21&offset=";
//        String  url =  String.format("https://sso.ifanr.com/api/v5/trochili/miniapp/?tag=&limit=%s&offset=%s",limit,offset);
//        zhixiaoSprider(url);
        int n = 21;
        for (int i = 0; i < 1000; i++) {
            String uu = url + n;
            System.out.println("哈哈哈" + n);
            zhixiaoSprider(uu);
            n = n + 21;
        }
    }

    @RequestMapping("appso")
    public void appso() {
        String url = "https://sso.ifanr.com/api/v5/wp/article/?post_type=app&limit=20&offset=";
        for (int i = 20; i < 1000000; i = i + 20) {
            String uu = url + i;
            System.out.println("appso" + i);
            String jsonStr = HttpClientUtil.doGet(uu);
            JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonStr);
            JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("objects"));
            for (int j = 0; j < jsonArray.size(); j++) {
                JSONObject obj = (JSONObject) jsonArray.get(j);
                Appso appso = JSON.toJavaObject(obj, Appso.class);
                Appso search = new Appso();
                search.setPost_id(appso.getPost_id());
                List<Appso> appsoList = appsoMapper.selectByExample(search);
                if(CollectionUtils.isEmpty(appsoList)){
                    try {
                        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date((Long.parseLong(appso.getPublished_at()) * 1000)));
                        appso.setPublished_at(time);
                        String time2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date((Long.parseLong(appso.getUpdated_at()) * 1000)));
                        appso.setUpdated_at(time2);
                        appso.setPost_content(EmojiConverterUtil.emojiConvert1(appso.getPost_content()));
                        appso.setPost_title(EmojiConverterUtil.emojiConvert1(appso.getPost_title()));
                        appso.setPost_excerpt(EmojiConverterUtil.emojiConvert1(appso.getPost_excerpt()));
                        appso.setId(null);
                        appsoMapper.insertSelective(appso);
                    } catch (Exception e) {
                        log.error("app so save {}", e.getMessage(), e);
                    }
                }else {
                    log.info("-----------------已存在-------------------");
                }
            }
        }

    }

    @RequestMapping("kuaixun")
    public void kuaixun() {
        String url = "https://zhishuapi.aldwx.com/Main/action/Dashboard/Homepage/newsFlash";
        Kuaixun kuaixun;
        for (int i = 1; i < 10000; i++) {
            System.out.println("page:" + i);
            String jsonStr = OkttpUtil.postData(url, i + "");
            JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonStr);
            JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("data"));
            for (int j = 0; j < jsonArray.size(); j++) {
                JSONObject obj = (JSONObject) jsonArray.get(j);
                kuaixun = JSON.toJavaObject(obj, Kuaixun.class);
                kuaixun.setPublicshAt(obj.getString("publicsh_at"));
                kuaixun.setId(null);
                List<Kuaixun> list = kuaixunService.getList(kuaixun);
                if (CollectionUtils.isEmpty(list)) {
                    try {
                        kuaixunService.save(kuaixun);
                    } catch (Exception e) {
                        log.error("kuaixunService save {}", e.getMessage(), e);
                    }
                }

            }
        }
    }

    public static void main(String[] args) throws Exception {
//        Unirest.setTimeouts(0, 5);
        HttpResponse<String> response = Unirest.post("https://zhishuapi.aldwx.com/Main/action/Dashboard/Homepage/newsFlash")
                .header("Content-Type", "application/json")
//                .multiPartContent()
//                .field("page", "5")
                .asString();

        String ss = "sfsfd";
    }


    // 知晓程序
    private void zhixiaoSprider(String url) {
        String jsonStr = HttpClientUtil.doGet(url);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonStr);
        String limit = ((JSONObject) JSONObject.parse(jsonObject.getString("meta"))).getString("limit");
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("objects"));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<LiebaoApp> liebaoJsonPojoList = new ArrayList<>();
        LiebaoApp liebao;
        for (int i = 0; i < jsonArray.size(); i++) {
            liebao = new LiebaoApp();
            JSONObject obj = (JSONObject) jsonArray.get(i);
            liebao.setAppId(Integer.parseInt(obj.getString("id")));
            liebao.setAppId(Integer.parseInt(obj.getString("id")));
            liebao.setAppSum(obj.getString("description"));
            liebao.setAppName(obj.getString("name"));
            LiebaoApp appByName = liebaoAppService.getAppByName(liebao.getAppName());
            if (appByName != null) {
                continue;
            }
            liebao.setAuthor("酷酷屋小程序");
            liebao.setHot(obj.getString("visit_amount"));
            liebao.setLogoUrl(((JSONObject) JSONObject.parse(obj.getString("icon"))).getString("image").substring(34));
            liebao.setQrUrl(((JSONObject) JSONObject.parse(obj.getString("qrcode"))).getString("image").substring(34));
            JSONArray screenshotArr = JSONArray.parseArray(obj.getString("screenshot"));
            String shotStr = "";
            for (int j = 0; j < screenshotArr.size(); j++) {
                JSONObject shotObj = (JSONObject) screenshotArr.get(j);
                shotStr += shotObj.getString("image") + ",";
            }
            if (shotStr.length() > 1) {
                liebao.setScrUrlsArr(shotStr.substring(0, shotStr.length() - 1));
            }

            JSONArray tagArr = JSONArray.parseArray(obj.getString("tag"));
            String tagStr = "";
            for (int k = 0; k < tagArr.size(); k++) {
                JSONObject tagObj = (JSONObject) tagArr.get(k);
                tagStr += tagObj.getString("name") + ",";
            }
            if (tagStr.length() > 1) {
                liebao.setTagsArr(tagStr.substring(0, tagStr.length() - 1));
            }
            liebao.setSourceId(2);
            liebao.setSourceUrl("minapp.com");
            liebao.setHomeType(3);
            try {
                liebao.setCreateTime(sdf.parse(Spridtest.timeStamp2Date(obj.getString("created_at"), null)));
            } catch (ParseException e) {
                e.printStackTrace();
            }
           boolean rel = liebaoJsonPojoList.add(liebao);
        }
        if (CollectionUtils.isEmpty(liebaoJsonPojoList)) {
            log.info("知晓无新增");
        } else {
            log.info("知晓新增：{}", liebaoJsonPojoList.size());
            liebaoAppService.saveAppList(liebaoJsonPojoList);
        }
    }

    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds + "000")));
    }

}
